/* 击注册按钮时，获取页面中5个input框中的数据去除空格，利用正则验证码输入格式是否正确，如果不正确进行提示
     并终止运行。发送请求进行注册，注册成功跳转到登录页
*/

class Register {
  constructor() {
    this.$("#submit").addEventListener("click", this.register.bind(this));
  }
  register() {
    let nickName = this.$("#nickName").value.trim();
    let userName = this.$("#userName").value.trim();
    let password1 = this.$("#password1").value.trim();
    let password2 = this.$("#password2").value.trim();
    let ver = this.$("#ver").value.trim();
    // console.log(userName, password1, password2, ver);
    let reg1 = /^[a-zA-Z0-9\w\-\u4e00-\u9fa5]{4,20}$/;
    let reg2 = /[a-zA-Z0-9]{6,20}/;
    if (!reg1.test(userName)) {
      layer.msg("用户名由4-20位字母数字汉字组成");
      return;
    }
    if (!reg2.test(password1)) {
      layer.msg("密码由6-20位字母数字组成");
      return;
    }
    if (password2 != password1) {
      layer.msg("两次输入密码不同");
      return;
    }
    if (ver != "jg77" && ver != "JG77") {
      layer.msg("验证码错误");
      return;
    }
    //设置编码格式
    axios.defaults.headers["Content-Type"] =
      "application/x-www-form-urlencoded";
    //请求数据
    //以字符串而不是json

    let param = `username=${userName}&password=${password1}&rpassword=${password2}&nickname=${nickName}`;
    axios
      .post("http://localhost:8888/users/register", param)
      .then(({ status, data }) => {
        // console.log(status, data);
        //判断状态
        if (status != 200 || data.code != 1) {
          layer.msg("注册失败");
          return;
        }
        if ((data.code = 1)) layer.msg("注册成功，即将跳转登录");
        setTimeout(() => {
          location.assign("./login.html");
        }, 2000);
      });
  }

  $(ele) {
    let arr = document.querySelectorAll(ele);
    return arr.length == 1 ? arr[0] : arr;
  }
}
new Register();
